package com.example.myapplication

import android.content.Context
import android.widget.Toast
import androidx.compose.animation.*
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material3.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.delay
import java.io.File
import androidx.compose.foundation.*
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.material3.*

// 🔹 定义可展开区块类型 (保持不变)
enum class MusicSection {
    ALL_MUSIC,
    FAVOURITE,
    PLAYLIST
}

@Composable
fun MainPage() {
    val context = LocalContext.current

    LaunchedEffect(Unit) {
        MusicPlayerManager.init(context)
    }

    var refreshTrigger by remember { mutableStateOf(0) }
    var isPlaying by remember { mutableStateOf(false) }

    LaunchedEffect(Unit) {
        while (true) {
            val playing = MusicPlayerManager.isPlaying()
            if (isPlaying != playing) isPlaying = playing
            if (MusicPlayerManager.getCurrentIndex() != StaticStorage.playIndex) {
                refreshTrigger++
            }
            delay(500)
        }
    }

    val currentPlayingFile: File? = if (StaticStorage.playList.isNotEmpty() &&
        StaticStorage.playIndex in StaticStorage.playList.indices) {
        StaticStorage.playList[StaticStorage.playIndex]
    } else null

    var expandedSection by rememberSaveable { mutableStateOf<MusicSection?>(MusicSection.ALL_MUSIC) }

    Box(
        modifier = Modifier
            .fillMaxSize()
            .padding(horizontal = 16.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                //.verticalScroll(rememberScrollState())
                .padding(bottom = 80.dp)
        ) {
            Text("用户名: ${AccountManager.ActiveAccount}", style = MaterialTheme.typography.titleMedium)
            Text(
                "本地曲库: ${StaticStorage.musicList.size} 首 | 播放列表: ${StaticStorage.playList.size} 首",
                color = MaterialTheme.colorScheme.primary,
                modifier = Modifier.padding(vertical = 4.dp)
            )

            Spacer(Modifier.height(16.dp))

            Card(modifier = Modifier.fillMaxWidth()) {
                Column(Modifier.padding(12.dp)) {
                    Text("正在播放", style = MaterialTheme.typography.labelSmall)
                    Text(
                        text = currentPlayingFile?.name ?: "没有正在播放的歌曲",
                        style = MaterialTheme.typography.titleMedium,
                        maxLines = 1,
                        color = MaterialTheme.colorScheme.primary
                    )
                    if (currentPlayingFile != null) {
                        Text(
                            text = "模式: ${StaticStorage.playMode} | 进度: ${formatTime(MusicPlayerManager.getCurrentPosition())}",
                            style = MaterialTheme.typography.bodySmall
                        )
                    }
                }
            }

            Spacer(Modifier.height(24.dp))

            ExpandableSection(
                title = "全部音乐 (${StaticStorage.musicList.size} 首)",
                isExpanded = expandedSection == MusicSection.ALL_MUSIC,
                onToggle = {
                    expandedSection = if (expandedSection == MusicSection.ALL_MUSIC) null else MusicSection.ALL_MUSIC
                },
                expandContent = {
                    LazyColumn(
                        modifier = Modifier.fillMaxWidth().heightIn(max = 400.dp),
                        verticalArrangement = Arrangement.spacedBy(4.dp)
                    ) {
                        itemsIndexed(StaticStorage.musicList) { _, file ->
                            SongItem(
                                songPath = file,
                                isPlaying = (currentPlayingFile?.absolutePath == file.absolutePath),
                                onClick = {
                                    //playOrAddToPlaylist(context, file)
                                    val idx = StaticStorage.musicList.indexOfFirst { it == file };
                                    StaticStorage.playList.clear();
                                    StaticStorage.playList.addAll(StaticStorage.musicList);
                                    StaticStorage.playIndex = idx;
                                    MusicPlayerManager.play(idx)
                                    refreshTrigger++
                                },
                                context = context
                            )
                        }
                    }
                }
            )

            Spacer(Modifier.height(16.dp))

            ExpandableSection(
                title = "我喜欢的音乐 (${StaticStorage.favouriteList.size} 首)",
                isExpanded = expandedSection == MusicSection.FAVOURITE,
                onToggle = {
                    expandedSection = if (expandedSection == MusicSection.FAVOURITE) null else MusicSection.FAVOURITE
                },
                expandContent = {
                    if (StaticStorage.favouriteList.isEmpty()) {
                        Text(
                            text = "暂无收藏~ 点击歌曲旁❤️添加",
                            style = MaterialTheme.typography.bodyMedium,
                            color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f),
                            modifier = Modifier.padding(16.dp)
                        )
                    } else {
                        LazyColumn(
                            modifier = Modifier.fillMaxWidth().heightIn(max = 400.dp),
                            verticalArrangement = Arrangement.spacedBy(4.dp)
                        ) {
                            itemsIndexed(StaticStorage.favouriteList) { _, file ->
                                SongItem(
                                    songPath = file,
                                    isPlaying = (currentPlayingFile?.absolutePath == file.absolutePath),
                                    onClick = {
                                        val idx = StaticStorage.favouriteList.indexOfFirst { it == file };
                                        StaticStorage.playList.clear();
                                        StaticStorage.playList.addAll(StaticStorage.favouriteList);
                                        StaticStorage.playIndex = idx;
                                        MusicPlayerManager.play(idx)
                                        refreshTrigger++
                                    },
                                    context = context
                                )
                            }
                        }
                    }
                }
            )

            Spacer(Modifier.height(16.dp))

            ExpandableSection(
                title = "播放列表 (${StaticStorage.playList.size} 首)",
                isExpanded = expandedSection == MusicSection.PLAYLIST,
                onToggle = {
                    expandedSection = if (expandedSection == MusicSection.PLAYLIST) null else MusicSection.PLAYLIST
                },
                expandContent = {
                    if (StaticStorage.playList.isEmpty()) {
                        Text(
                            text = "暂无播放列表~",
                            style = MaterialTheme.typography.bodyMedium,
                            color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f),
                            modifier = Modifier.padding(16.dp)
                        )
                    } else {
                        LazyColumn(
                            modifier = Modifier.fillMaxWidth().heightIn(max = 400.dp),
                            verticalArrangement = Arrangement.spacedBy(4.dp)
                        ) {
                            itemsIndexed(StaticStorage.playList) { _, file ->
                                SongListItem(
                                    songPath = file,
                                    isPlaying = (currentPlayingFile?.absolutePath == file.absolutePath),
                                    onClick = {
                                        MusicPlayerManager.play(index = StaticStorage.playList.indexOfFirst { it == file })
                                        StaticStorage.playIndex = StaticStorage.playList.indexOfFirst { it == file };
                                        refreshTrigger++
                                    },
                                    context = context
                                )
                            }
                        }
                    }
                }
            )

            Spacer(Modifier.height(24.dp))
        }

        if (currentPlayingFile != null) {
            val duration = MusicPlayerManager.getDuration().coerceAtLeast(1L)
            val currentPosition = MusicPlayerManager.getCurrentPosition().coerceIn(0L, duration)

            val progressRatio = remember { mutableStateOf(currentPosition.toFloat() / duration.toFloat()) }
            var isUserDragging by remember { mutableStateOf(false) }

            // 自动同步进度（非拖动时）
            LaunchedEffect(isPlaying, isUserDragging) {
                while (isPlaying && !isUserDragging) {
                    val pos = MusicPlayerManager.getCurrentPosition().coerceIn(0L, duration)
                    progressRatio.value = pos.toFloat() / duration.toFloat()
                    delay(300)
                }
            }

            Box(
                modifier = Modifier
                    .align(Alignment.BottomCenter)
                    .fillMaxWidth()
                    .height(64.dp) // 高度包含 Slider + 时间文本
                    .background(MaterialTheme.colorScheme.surface)
                    .padding(horizontal = 16.dp)
            ) {
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally,
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Slider(
                        value = progressRatio.value,
                        onValueChange = { ratio ->
                            isUserDragging = true
                            progressRatio.value = ratio
                        },
                        onValueChangeFinished = {
                            isUserDragging = false
                            MusicPlayerManager.seekToRatio(progressRatio.value)
                        },
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(10.dp)
                            .padding(horizontal = 8.dp),
                        colors = SliderDefaults.colors(
                            thumbColor = MaterialTheme.colorScheme.primary,
                            activeTrackColor = MaterialTheme.colorScheme.primary
                        )
                    )
                    Spacer(Modifier.height(5.dp))
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        Text(
                            text = formatTime(currentPosition),
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                        Text(
                            text = formatTime(duration),
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }

                    Row(
                        horizontalArrangement = Arrangement.Center,
                        verticalAlignment = Alignment.CenterVertically,
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(horizontal = 32.dp) // 左右留白，避免贴边
                    ) {
                        IconButton(
                            onClick = {
                                MusicPlayerManager.prev()
                                refreshTrigger++
                            },
                            enabled = StaticStorage.musicList.isNotEmpty() || StaticStorage.playList.isNotEmpty()
                        ) {
                            Icon(
                                imageVector = Icons.Default.SkipPrevious,
                                contentDescription = "Previous",
                                modifier = Modifier.size(36.dp)
                            )
                        }

                        IconButton(
                            onClick = {
                                if (MusicPlayerManager.isPlaying())
                                {
                                    MusicPlayerManager.pause()
                                }
                                else
                                {
                                    if (StaticStorage.playList.isEmpty() && StaticStorage.musicList.isNotEmpty())
                                    {
                                        StaticStorage.playList.addAll(StaticStorage.musicList)
                                        MusicPlayerManager.play(0)
                                    }
                                    else
                                    {
                                        MusicPlayerManager.resume()
                                        if (!MusicPlayerManager.isLoaded()) MusicPlayerManager.play(MusicPlayerManager.getCurrentIndex())
                                    }
                                }
                                refreshTrigger++
                            },
                            enabled = StaticStorage.musicList.isNotEmpty() || StaticStorage.playList.isNotEmpty()
                        ) {
                            Icon(
                                imageVector = if (isPlaying) Icons.Default.Pause else Icons.Default.PlayArrow,
                                contentDescription = if (isPlaying) "Pause" else "Play",
                                modifier = Modifier.size(48.dp) // 播放按钮最大，突出主操作
                            )
                        }

                        IconButton(
                            onClick = {
                                MusicPlayerManager.next()
                                refreshTrigger++
                            },
                            enabled = StaticStorage.musicList.isNotEmpty() || StaticStorage.playList.isNotEmpty()
                        ) {
                            Icon(
                                imageVector = Icons.Default.SkipNext,
                                contentDescription = "Next",
                                modifier = Modifier.size(36.dp)
                            )
                        }
                    }

                }
            }
        }
    }
}

// 🔹 辅助逻辑：点击歌曲时的行为
fun playOrAddToPlaylist(context: Context, file: File) {
    // 1. 检查播放列表中是否已有该歌曲
    val existingIndex = StaticStorage.playList.indexOfFirst { it.absolutePath == file.absolutePath }

    if (existingIndex != -1) {
        // A. 如果有，直接切到这一首
        MusicPlayerManager.play(existingIndex)
        Toast.makeText(context, "切歌: ${file.name}", Toast.LENGTH_SHORT).show()
    } else {
        // B. 如果没有，添加到末尾，然后播放
        StaticStorage.playList.add(file)
        val newIndex = StaticStorage.playList.lastIndex
        MusicPlayerManager.play(newIndex)
        Toast.makeText(context, "已添加并播放: ${file.name}", Toast.LENGTH_SHORT).show()
    }
}

// 🔹 辅助函数：格式化时间 (毫秒 -> mm:ss)
fun formatTime(millis: Long): String {
    val totalSeconds = millis / 1000
    val minutes = totalSeconds / 60
    val seconds = totalSeconds % 60
    return String.format("%02d:%02d", minutes, seconds)
}

@Composable
private fun SongItem(
    songPath: File,
    isPlaying: Boolean,
    onClick: () -> Unit,
    context: Context
) {
    // 监听收藏状态变化
    var isFav by remember { mutableStateOf(songPath in StaticStorage.favouriteList) }

    Row(
        modifier = Modifier.fillMaxWidth(),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Card(
            modifier = Modifier
                .weight(1f)
                .clickable(onClick = onClick)
                .padding(vertical = 4.dp),
            colors = CardDefaults.cardColors(
                containerColor = if (isPlaying)
                    MaterialTheme.colorScheme.primaryContainer
                else
                    MaterialTheme.colorScheme.surface
            ),
            elevation = CardDefaults.elevatedCardElevation(defaultElevation = 1.dp)
        ) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 12.dp, vertical = 12.dp)
            ) {
                // 如果正在播放，前面加个小图标
                if (isPlaying) {
                    Icon(
                        imageVector = Icons.Default.PlayArrow,
                        contentDescription = null,
                        modifier = Modifier.size(16.dp).align(Alignment.CenterVertically),
                        tint = MaterialTheme.colorScheme.primary
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                }

                Text(
                    text = songPath.name,
                    style = MaterialTheme.typography.bodyMedium,
                    maxLines = 1,
                    modifier = Modifier.weight(1f)
                )
            }
        }

        // 收藏按钮
        IconButton(
            onClick = {
                if (isFav) {
                    StaticStorage.favouriteList.remove(songPath)
                } else {
                    StaticStorage.favouriteList.add(songPath)
                }
                saveFileListToFile(context, "cache/Favourite.dat", StaticStorage.favouriteList)
                isFav = !isFav // 触发 UI 刷新
            },
            modifier = Modifier.size(48.dp)
        ) {
            Icon(
                imageVector = if (isFav) Icons.Default.Favorite else Icons.Default.FavoriteBorder,
                contentDescription = if (isFav) "已收藏" else "收藏",
                tint = if (isFav) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant
            )
        }

        //添加至播放列表
        IconButton(
            onClick = {
                if (songPath !in StaticStorage.playList)
                {
                    StaticStorage.playList.add(songPath);
                }
            },
            modifier = Modifier.size(48.dp)
        ) {
            Icon(
                imageVector = Icons.Default.Add,
                contentDescription = "",
            )
        }
    }
}

@Composable
private fun SongListItem(
    songPath: File,
    isPlaying: Boolean,
    onClick: () -> Unit,
    context: Context
) {
    var index by remember { mutableStateOf(  StaticStorage.playList.indexOfFirst { it == songPath }) }
    Row(
        modifier = Modifier.fillMaxWidth(),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Card(
            modifier = Modifier
                .weight(1f)
                .clickable(onClick = onClick)
                .padding(vertical = 4.dp),
            colors = CardDefaults.cardColors(
                containerColor = if (isPlaying)
                    MaterialTheme.colorScheme.primaryContainer
                else
                    MaterialTheme.colorScheme.surface
            ),
            elevation = CardDefaults.elevatedCardElevation(defaultElevation = 1.dp)
        ) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 12.dp, vertical = 12.dp)
            ) {
                // 如果正在播放，前面加个小图标
                if (isPlaying) {
                    Icon(
                        imageVector = Icons.Default.PlayArrow,
                        contentDescription = null,
                        modifier = Modifier.size(16.dp).align(Alignment.CenterVertically),
                        tint = MaterialTheme.colorScheme.primary
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                }

                Text(
                    text = songPath.name,
                    style = MaterialTheme.typography.bodyMedium,
                    maxLines = 1,
                    modifier = Modifier.weight(1f)
                )
            }
        }

        //移除播放列表
        if (index != StaticStorage.playIndex)
        {
            IconButton(
                onClick = {
                    if (songPath in StaticStorage.playList)
                    {
                        StaticStorage.playList.remove(songPath);
                        if (index < StaticStorage.playIndex) --StaticStorage.playIndex;
                    }
                },
                modifier = Modifier.size(48.dp)
            ) {
                Icon(
                    imageVector = Icons.Default.Remove,
                    contentDescription = "",
                )
            }
        }
    }
}

@Composable
fun ExpandableSection(
    title: String,
    isExpanded: Boolean,
    onToggle: () -> Unit,
    expandContent: @Composable () -> Unit,
    modifier: Modifier = Modifier
) {
    Column(modifier = modifier) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .clickable { onToggle() }
                .padding(vertical = 8.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = title,
                style = MaterialTheme.typography.titleMedium,
                modifier = Modifier.weight(1f)
            )
            Icon(
                imageVector = if (isExpanded) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown,
                contentDescription = if (isExpanded) "收起" else "展开",
                tint = MaterialTheme.colorScheme.primary
            )
        }

        Divider(thickness = 0.5.dp, color = MaterialTheme.colorScheme.outlineVariant)

        AnimatedVisibility(
            visible = isExpanded,
            enter = fadeIn() + expandVertically(expandFrom = Alignment.Top),
            exit = fadeOut() + shrinkVertically(shrinkTowards = Alignment.Top)
        ) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 8.dp)
            ) {
                expandContent()
            }
        }
    }
}